package edu.nf.exam.controller;

import cn.hutool.core.io.file.FileNameUtil;
import edu.nf.exam.entity.UserInfo;
import edu.nf.exam.service.impl.UserServiceImpl;
import edu.nf.exam.util.HttpUtils;
import edu.nf.exam.util.UUIDUtil;
import org.nf.mvc.annotation.RequestMapping;
import org.nf.mvc.servlet.View;
import org.nf.mvc.view.JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;



/**
 * 文件上传
 * @author wangl
 * @date 2021/6/7
 */
public class UploadController extends BaseController{

    @RequestMapping("/file/upload")
    public View uploadFiles(HttpServletRequest request,UserInfo userInfo){

        System.out.println(userInfo);
        try {
            //HFS远程上传地址
            String url = "http://localhost:1801/image/";
            int code=0;
            String fileName= null;

            //循环Parts集合
            for(Part part : request.getParts()){
                if(part.getSubmittedFileName()!=null){
                    System.out.println(part.getSubmittedFileName());
                    // 获取文件的后缀名
                    String extName = FileNameUtil.extName(part.getSubmittedFileName());
                    // 重新定义文件名
                    fileName = UUIDUtil.createUUID()+"."+extName;
                    // code == 200 就是成功
                    code=HttpUtils.upload(url,fileName,part.getInputStream());

                }
            }
            System.out.println(fileName);
            System.out.println(code);
            if(code==200){
                // 删除原来的远程服务器图片
                HttpUtils.delServiceFile(url,userInfo.getImage());
                userInfo.setImage(fileName);
                // 修改用户头像信息
                new UserServiceImpl().checkUpdate(userInfo);
            }
            // 返回layui上传成功状态码
            return new JsonView(success(0,fileName));
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonView(fail(500,"上传失败"));
        }

    }
}
